package com.fone.player.activity.main;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.widget.ImageView;

import com.fone.player.ApplicationManage;
import com.fone.player.R;
import com.fone.player.activity.BaseActivity;
import com.fone.player.client.Callback;
import com.fone.player.client.Error;
import com.fone.player.client.LoginRst;
import com.fone.player.client.Request;
import com.fone.player.constant.FoneConstant;
import com.fone.player.entity.Download;
import com.fone.player.entity.RedirectInfo;
import com.fone.player.service.FoneServiceManager;
import com.fone.player.storage.SharedPreferenceModule;
import com.fone.player.storage.StorageModule;
import com.fone.player.storage.download.DownloadUtil;
import com.fone.player.util.Activity2poster;
import com.fone.player.util.FoneUtil;
import com.fone.player.util.GetFileSizeUtil;
import com.fone.player.util.L;
import com.fone.player.util.SystemUtil;
import com.fone.player.view.WeixinDownloadDialog;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

public class SplashActivity extends BaseActivity {

	private static final String TAG = "SplashActivity";
	private ImageView imageView;
	private static final int SUCCESS = 0;

	private String shost;

	private String ad_pic;
	private String ad_utp;
	private String ad_url;
	private String ad_name;

	private int ad_time = 10;
	private boolean isFirst = false;

	DisplayImageOptions options;

	private Handler handler;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_splash);

		L.v(TAG, "onCreate", "---- start scaning local media in fastMode----");
		StorageModule.getInstance().scanningExternalStorage();
		// 开启离线缓存service
		StorageModule.getInstance().startCacheService();

		if (!L.mode_for_release) {
			// copy数据库到文件夹
			StorageModule.getInstance().copyDataBaseToSdCard();
		}

		initView();
		initData();
		isUpdateSuccess();// 升级成功上报处理
		handler = new Handler() {

			@Override
			public void handleMessage(Message msg) {

				Log.v("SplashActivity", "SplashActivity handleMessage");

				if (ad_pic != null) {
					ImageLoader.getInstance().displayImage(
							FoneUtil.getAbsoluteUrl("", shost, ad_pic),
							imageView, options);
					showAD();
				} else {

					goMain();

				}
			}
		};
		doCleanCacheFolder();
		// handler.sendEmptyMessageDelayed(0, 3000);

		AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
		Intent i = new Intent("com.fone.notifyservice");
		PendingIntent pi = PendingIntent.getBroadcast(this, 11, i,
				PendingIntent.FLAG_UPDATE_CURRENT);
		am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 600000, pi);
	}

	@Override
	protected void onResume() {
		super.onResume();
		Log.v("SplashActivity", "SplashActivity onResume");
		handler.sendEmptyMessageDelayed(0, 3000);

	}

	@Override
	protected void onPause() {
		super.onPause();
		Log.v("SplashActivity", "SplashActivity onPause");
		handler.removeMessages(0);

	}

	private void initView() {
		imageView = (ImageView) findViewById(R.id.pic_ad);
		// imageView.setScaleType(ScaleType.FIT_XY);
		imageView.setOnClickListener(new ImageClicker());

		options = new DisplayImageOptions.Builder()
				.showImageOnLoading(R.drawable.start_default)
				.showImageForEmptyUri(R.drawable.start_default)
				.showImageOnFail(R.drawable.start_default).cacheInMemory(false)
				.cacheOnDisk(true).considerExifParams(true).build();
	}

	private void initData() {
		L.v(TAG, "initData", "login");
		// 初始化wifi开关(默认开启 需同步SP中数据)
		boolean isWifiChecked = SharedPreferenceModule.getInstance()
				.getBoolean(FoneConstant.AUTO_DOWNLOAD_FLAG_SP, true);
		SharedPreferenceModule.getInstance().setBoolean(
				FoneConstant.AUTO_DOWNLOAD_FLAG_SP, isWifiChecked);

		// 如果没有网络，则不向服务器申请数据
		if (FoneUtil.isNetOkWithToast(SplashActivity.this)) {
			Request.getInstance().login(0, new SplashCallback());
			FoneUtil.requestDeclarations(SplashActivity.this
					.getApplicationContext());// 请求声明 提示语 分享语
		} else {
			// goMain();
		}
	}

	private class SplashCallback implements Callback<LoginRst> {

		@Override
		public void onSuccess(LoginRst t) {

			L.v(TAG, "SplashCallback", "-onSuccess-" + t.result);

			if (t.result == SUCCESS) {
				FoneConstant.loginRst = t;
				shost = t.shost;
				// 将栏目列表信息取出
				ApplicationManage.getAplicationManageInstance().labelList
						.setMnList(t.mns.mnList);

				// 如果有升级包 根据网络判断是否需要下载.
				if (DownloadUtil.getNetType() == StorageModule.MSG_WIFI_NETWORK_TYPE) {
					// TODO 请求下载APK
					Download download = new Download();
					download.setDownloadFileName(t.softupdate.name);
					download.setDownloadDesc(t.softupdate.updatedesc);
					download.setDownloadIsShowRunningNotification(false);
					download.setDownloadIsShowFinishNotification(false);
					download.setDownloadUrl(t.softupdate.updateurl);
					download.setDownloadIsInstall(false);
					download.setDownloadIsErrorToast(false);
					download.setDownloadIsLimitSpeed(true);
					download.setDownloadType(Download.DOWNLOAD_UPGRADE);
					download.setDownloadNotification(mContext);
					StorageModule.getInstance().addFileDownload(download);

					// 判断服务器数据是否返回广告页内容
					if (t.posters != null && t.posters.posterList != null
							&& t.posters.posterList.size() > 0) {

						if (TextUtils.isEmpty(t.posters.posterList.get(0).time)) {
							ad_time = 3000;
						} else {
							ad_time = new Integer(
									t.posters.posterList.get(0).time) * 1000;
						}

						ad_pic = t.posters.posterList.get(0).pic;
						ad_name = t.posters.posterList.get(0).name;
						ad_url = t.posters.posterList.get(0).url;
						ad_utp = t.posters.posterList.get(0).utp;

						// showShortToast("ad_time = " + ad_time);

						// ImageLoader.getInstance().displayImage(
						// FoneUtil.getAbsoluteUrl("", shost, ad_pic),
						// imageView, options);
						// showAD();
					} else {
						// imageView
						// .setBackgroundResource(R.drawable.start_default);
						// showAD();
					}
				} else {
					// goMain();
				}

				if (!TextUtils.isEmpty(t.weixinurl)) {
					SharedPreferenceModule.getInstance().setString(
							WeixinDownloadDialog.WEIXIN_DOWNLOAD_URL,
							t.weixinurl);
				}

			} else {
				// goMain();
			}

		}

		@Override
		public void onFailure(Error error) {
			L.v(TAG, "SplashCallback", "-onFailure-" + error.toString());
			// goMain();
		}

	}

	private void showAD() {
		if (ad_time > 3000) {
			ad_time = 3000;
		}

		// ImageView maskView = (ImageView) findViewById(R.id.pic_icon);

		// maskView.setVisibility(View.INVISIBLE);

		View view = findViewById(R.id.splash_pic_def);

		// 动画效果参数直接定义
		Animation animation = new AlphaAnimation(0.1f, 1.0f);
		animation.setDuration(ad_time);
		imageView.setAnimation(animation);

		animation = new AlphaAnimation(0.5f, 0f);
		animation.setDuration(ad_time);
		view.setAnimation(animation);

		animation.setAnimationListener(new AnimationListener() {

			@Override
			public void onAnimationStart(Animation animation) {
			}

			@Override
			public void onAnimationRepeat(Animation animation) {
			}

			@Override
			public void onAnimationEnd(Animation animation) {
				View view = findViewById(R.id.splash_pic_def);
				view.setVisibility(View.INVISIBLE);
				goMain();
			}
		});
	}

	private void goMain() {
		Intent intent = new Intent(SplashActivity.this, MainTabActivity.class);
		startActivity(intent);
		// overridePendingTransition(R.anim.push_up_in, 0);
		finish();

	}

	private class ImageClicker implements OnClickListener {

		@Override
		public void onClick(View v) {
			// 0 下载应用，1 进入详情页
			if (TextUtils.isEmpty(ad_utp)) {

			} else if (ad_utp.equals("0")) {
				if (!TextUtils.isEmpty(ad_url) && !isFirst) {
					showShortToast("已开始下载" + ad_name + "软件");
					FoneServiceManager.getFoneServiceManager(
							SplashActivity.this).loadAPK(ad_url, ad_name);
					isFirst = true;
				}
			} else if (ad_utp.equals("1") && !TextUtils.isEmpty(ad_url)) {
				RedirectInfo info = new RedirectInfo();
				info.utp = new Integer(ad_utp);
				info.url = ad_url;
				info.vgurl = ad_url;
				info.xyzplayurl = ad_url;
				Activity2poster.startActivity(SplashActivity.this, info);
			}
		}

	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
	}

	/**
	 * 判断是否成功升级 并处理上报
	 * 
	 * @return void
	 * @throws
	 */
	private void isUpdateSuccess() {
		String versionCode = SharedPreferenceModule.getInstance().getString(
				FoneConstant.UPDATE_VERSION);
		String currentVersion = SystemUtil.getAppVersion(mContext);
		if (!TextUtils.isEmpty(versionCode)) {
			// sp中存在版本号(即以前有点击升级)
			L.v("测试", "version code in sp is " + versionCode
					+ "!,need to judge wheater report or not");
			if (versionCode.equals(currentVersion)) {
				// 版本号一致
				L.v("测试", "current version code in sp is " + currentVersion
						+ "!, won't report");
			} else {
				// FIXME 版本号不一致(因无法覆盖安装低版本,故该情况只能是升级成功) 处理上报点
				// Reporter.logEvent();
				// 上报以后需要修改记录的versioncode
				SharedPreferenceModule.getInstance().setString(
						FoneConstant.UPDATE_VERSION, currentVersion);
			}

		} else {
			// SP中不存在版本号(新用户直接安装)
			L.v("测试",
					"version code in sp is null! won't report the type of update success!");
		}
	}

	/**
	 * 清理缓存文件夹
	 * 
	 * @return void
	 * @throws
	 */
	private void doCleanCacheFolder() {
		long fileSize = 0;
		String path = SystemUtil
				.getFoneCacheFolder(SystemUtil.ONLINE_CACHE_TYPE);
		try {

			fileSize = GetFileSizeUtil.getInstance().getFileSizeByPath(path);
		} catch (Exception e) {
			e.printStackTrace();

		}
		if (fileSize > 0) {
			SystemUtil.delAllFile(path);
		}
	}

}
